package com.sptpc.learnspring.controller;

import com.sptpc.learnspring.controller.request.NewDrinkRequest;
import com.sptpc.learnspring.model.Category;
import com.sptpc.learnspring.model.Drink;
import com.sptpc.learnspring.service.ICategoryService;
import com.sptpc.learnspring.service.IDrinkService;
import com.sptpc.learnspring.vo.DrinkListVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

@Slf4j
@RestController
@RequestMapping("/drink")
public class DrinkController {
    @Autowired
    private IDrinkService drinkService;
    @Autowired
    private ICategoryService categoryService;

    // 前端使用json提交数据
    @PostMapping(value = "/add/v2", consumes = {MediaType.APPLICATION_JSON_VALUE})
    public Drink addNewDrink(@RequestBody @Valid NewDrinkRequest newDrink) {
        log.info("创建新饮品{}", newDrink);
        Category category = categoryService.getCategoryById(newDrink.getCategory());
        Drink drink = new Drink();
        BeanUtils.copyProperties(newDrink, drink);
        drink.setCreateTime(LocalDate.now());
        drink.setCategory(category);
        drink = drinkService.addNewDrink(drink);
        log.info("创建成功");
        return drink;
    }

    @GetMapping("/")
    public List<Drink> listDrinks() {
        log.info("查询饮品菜单");
        return drinkService.getAllDrinks();
    }

    @GetMapping("/{id}")
    public Drink getDrinkById(@PathVariable Long id) {
        log.info("查询饮品，id: {}", id);
        Optional<Drink> drinkOptional = drinkService.getDrinkById(id);
        if (drinkOptional.isPresent()) {
            return drinkOptional.get();
        } else {
            return null;
        }
    }

    @PostMapping("/")
    // 函数参数需与前端http参数名字相同
    public DrinkListVO searchDrinks(String key) {
        log.info("搜索饮品 key: {}", key);
        List<Drink> list = drinkService.searchDrinksByKey("%"+key+"%");
        DrinkListVO result = new DrinkListVO();
        result.setCount((long) list.size());
        result.setData(list);
        return result;
    }

    @GetMapping("/c/{cid}")
    // 通过分类id查找其下饮品
    public DrinkListVO getDrinksByCategory(@PathVariable Long cid) {
        log.info("查询分类下的饮品菜单");
        List<Drink> list = drinkService.searchDrinksByCategory(cid);
        DrinkListVO result = new DrinkListVO();
        result.setCount((long) list.size());
        result.setData(list);
        return result;
    }

}
